const express = require('express');
const router = express.Router();
const R = require("../util/json")
const connection = require("../util/db")
const json = require("../util/jsonFormat")
const multer = require("multer");
const fs = require("fs");
const ResultJson = require("../util/json");
const request = require('request')

function extracted(car, sql, objs) {
    if (car.carNo) {
        sql += "and car_no like ? ";
        objs.push(`%${car.carNo}%`)
    }
    if (car.brandId) {
        sql += "and brand_id = ? ";
        objs.push(car.brandId)
    }
    if (car.type) {
        sql += "and type = ? ";
        objs.push(car.type)
    }
    if (car.status) {
        sql += "and status = ? ";
        objs.push(car.status)
    }
    return sql;
}

router.get("/page",function (req, res) {
    const car = req.query;
    const {page=1,limit=5} = car;
    let sql = "select c.*,b.brand_name,b.ps from car c left join brand b on c.brand_id = b.id where 1 = 1 ";
    let objs = [];
    sql = extracted(car, sql, objs);
    sql+="order by id desc limit ?,?";
    objs.push((page-1)*limit,parseInt(limit));
    connection.query(sql,objs,function (e,carList) {
        if(e){
            throw e;
        }
        sql = "select count(id) count from car where 1 = 1 ";
        objs=[];
        sql=extracted(car,sql,objs);
        connection.query(sql,objs,function (e,r) {
            if(e){
                throw e;
            }
            res.json(R.page(r[0].count,json.formatArray(carList)));
        })
    })



})
router.get("/info/:id",function (req, res) {
    const id = req.params.id;
    connection.query("select c.*,b.brand_name,b.ps from car c left join brand b on c.brand_id = b.id where c.id = ? ",[id],function (e,r) {
        if(e){
            throw e;
        }
        if(r.length !== 1){
            res.json(R.error("编号异常"))
        }else{
            res.json(R.data(json.formatObject(r[0])));
        }
    })
})
router.delete("/delete/:id",function (req, res) {
    const id = req.params.id;
    connection.query("select * from apply where apply_status = 4 and car_id = ?",[id],function (e,r) {
        if(e){
            throw e;
        }
        if(r.length>0){
            res.json(R.error("该车正在使用，禁止删除!"))
        }else{
            connection.query("delete from car where id = ?",[id],function (e) {
                if(e){
                    throw e;
                }
                res.json(R.ok());
            })
        }
    })
});
router.post("/update",function (req, res) {
    const car = req.body;
    if(car.id){
        connection.query("select * from car where car_no = ?",[car.carNo],function (e,r) {
            if(e){
                throw e;
            }
            if(r.length>0 && r[0].id != car.id){
                res.json(R.error("车牌号已存在！"))
            }else{
                let sql = "update car set car_no = ?,color = ?,brand_id = ?,type = ?,status = ?,car_no_image = ? where id = ?";
                let objs=[car.carNo,car.color,car.brandId,car.type,car.status,car.carNoImage,car.id];
                connection.query(sql,objs,function (e) {
                    if(e){
                        throw e;
                    }
                    /*删除之前的图片*/
                    connection.query("delete from car_image where car_id = ?",[car.id],function (e) {
                        if(e){
                            throw e
                        }
                        /*批量添加图片*/
                        batchImage(car.id,car.imageList,res);
                    })
                })
            }
        })
    }else{
        connection.query("select * from car where car_no = ?",[car.carNo],function (e,r) {
            if(e){
                throw e;
            }
            if(r.length>0){
                res.json(R.error("车牌号已存在！"))
            }else{
                let sql = "insert into car values(null,?,?,?,?,?,?)";
                let objs=[car.carNo,car.color,car.brandId,car.type,car.status,car.carNoImage];
                connection.query(sql,objs,function (e) {
                    if(e){
                        throw e;
                    }
                    connection.query("select last_insert_id() insertId",[],function (e,r) {
                        const carId = r[0].insertId;
                        const imageList = car.imageList;
                        batchImage(carId,imageList,res)
                    })

                })
            }
        })

    }
})
const batchImage=function(carId,imageList,res){
    if(imageList){
        const il = imageList.split(",");
        if(il.length>0){
            let sql = "insert into car_image values";
            let objs=[];
            for(const image of il){
                sql+="(null,?,?),";
                objs.push(carId,image);
            }
            sql=sql.substring(0,sql.length-1);
            connection.query(sql,objs,function (e) {
                if(e){
                    throw e
                }
                res.json(R.ok())
            })
        }else{
            res.json(R.ok());
        }
    }else{
        res.json(R.ok())
    }

}
router.post("/status",function (req, res) {
    const {id,status} = req.body;
    connection.query("update car set status = ? where id = ?",[status,id],function (e) {
        if(e){
            throw e;
        }
        res.json(R.ok());
    })
})
router.get("/images/:id",function (req,res) {
    const id = req.params.id;
    connection.query("select * from car_image where car_id = ?",[id],function (e,r) {
        if(e){
            throw e;
        }
        res.json(R.data(json.formatArray(r)))
    })
})
router.get("/use/select",function (req,res) {
    let {applyStartTime,applyEndTime} = req.query;
    let sql = "select c.*,a.id aid,b.brand_name brandName from car c left join (select * from apply where apply_status = 4 and (? > apply_end_time or ? < apply_start_time)) a on c.id = a.adm_car_id left join brand b on c.brand_id = b.id";
    let objs = [applyStartTime,applyEndTime];
    connection.query(sql,objs,function (e,r) {
        if(e){
            throw e
        }
        res.json(R.data(json.formatArray(r)));
    })
})

router.post('/carno', multer({dest: "./temp"}).single("file"), function (req, res) {
    fs.readFile(req.file.path, function (e, d) {
        let ons = req.file.originalname.split(".");
        let fileType = ons[ons.length - 1];
        let fileName = req.file.filename + "." + fileType;
        fs.writeFile(`./public/upload/${fileName}`, d, function (e) {
            if (e) {
                fs.unlinkSync("./temp/" + req.file.filename);//删除临时文件
                throw e;
            }
            fs.unlinkSync("./temp/" + req.file.filename);//删除临时文件
            const AK = '4Bh00xaxIX1lfVVUUbMaYNmk';
            const SK = 'EhjsfzTioglo7QFror4xngCuP2mjrL4k';
            request({
                'method': 'POST',
                'url': `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${AK}&client_secret=${SK}`,
            }, (error, response) => {
                if (error) {
                    console.log(error)
                }
                else {
                    const token = JSON.parse(response.body).access_token;
                    const options = {
                        'method': 'POST',
                        'url': 'https://aip.baidubce.com/rest/2.0/ocr/v1/license_plate?access_token=' + token,
                        'headers': {
                            'Content-Type': 'application/x-www-form-urlencoded',
                            'Accept': 'application/json'
                        },
                        form: {
                            'image': getFileContentAsBase64(`./public/upload/${fileName}`),
                            'multi_detect': 'false',
                            'multi_scale': 'false'
                        }
                    };
                    request(options, function (error, response) {
                        if (error) throw new Error(error);
                        const json = JSON.parse(response.body);
                        if(json.error_code){
                            res.json(ResultJson.error("无法识别车牌！"))
                        }else{
                            res.json(ResultJson.data({fileName,carNo:JSON.parse(response.body).words_result.number}))
                        }

                    });

                }
            })




        })
    })
})
/**
 * 获取文件base64编码
 * @param string  path 文件路径
 * @return string base64编码信息，不带文件头
 */
function getFileContentAsBase64(path) {
    const fs = require('fs');
    try {
        return fs.readFileSync(path, { encoding: 'base64' });
    } catch (err) {
        throw new Error(err);
    }
}
module.exports = router;
